//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package api_common

import (
	"context"
	"fmt"

	"atomgit.com/openlinksaas/api-server/dao/org_dao"
	"atomgit.com/openlinksaas/api-server/dao/project_dao"
	"atomgit.com/openlinksaas/api-server/notice_serv"
	"google.golang.org/protobuf/proto"
)

func SendNoticeToUser(ctx context.Context, userId string, notice proto.Message) error {
	return notice_serv.PublishToUser(userId, notice)
}

func SendNoticeToProjectScope(ctx context.Context, projectId string, notice proto.Message) error {
	memberItemList, err := project_dao.MemberInfoDao.ListMember(ctx, projectId)
	if err != nil {
		return err
	}
	for _, memberItem := range memberItemList {
		err = notice_serv.PublishToUser(memberItem.MemberUserId, notice)
		if err != nil {
			fmt.Println(err)
			return err
		}
	}
	return nil
}

func SendNoticeToOrgScope(ctx context.Context, orgId string, notice proto.Message) error {
	memberItemList, err := org_dao.MemberDao.ListByOrg(ctx, orgId)
	if err != nil {
		return err
	}
	for _, memberItem := range memberItemList {
		err = notice_serv.PublishToUser(memberItem.MemberUserId, notice)
		if err != nil {
			fmt.Println(err)
			return err
		}
	}
	return nil
}

// 只发送给管理员
func SendNoticeToProjectAdminScope(ctx context.Context, projectId string, notice proto.Message) error {
	userIdMap := map[string]bool{}
	projectItem, err := project_dao.ProjectInfoDao.Get(ctx, projectId)
	if err != nil {
		return err
	}
	userIdMap[projectItem.OwnerUserId] = true
	roleItemList, err := project_dao.MemberRoleDao.ListByProjectId(ctx, projectId)
	if err != nil {
		return err
	}
	roleItemMap := map[string]*project_dao.RoleInfoDbItem{}
	for _, roleItem := range roleItemList {
		roleItemMap[roleItem.RoleId] = roleItem
	}
	memberItemList, err := project_dao.MemberInfoDao.ListMember(ctx, projectId)
	if err != nil {
		return err
	}
	for _, memberItem := range memberItemList {
		roleItem, ok := roleItemMap[memberItem.RoleId]
		if !ok {
			continue
		}
		if roleItem.BasicInfo.Admin {
			userIdMap[memberItem.MemberUserId] = true
		}
	}
	for userId, _ := range userIdMap {
		err = notice_serv.PublishToUser(userId, notice)
		if err != nil {
			fmt.Println(err)
			return err
		}
	}
	return nil
}
